#include "analyzer_common.h"

int analyzer_prune(sparse_matrix_t* s, sparse_matrix_t* s_new){
    s_new->m = s->m;
    s_new->n = s->n;
    s_new->nnz = 0;
    s_new->rowpointer = malloc(sizeof(sparse_pointer_t) * (s_new->m + 1));
    memset(s_new->rowpointer, 0, sizeof(sparse_pointer_t) * (s_new->m + 1));
    for(sparse_index_t row = 0; row < s->m; row++){
        for(sparse_pointer_t idx = s->rowpointer[row]; idx < s->rowpointer[row+1]; idx++){
            // if(s->value[idx] != 0){ // (2)
            // if(fabs(s->value[idx]) > 1e-40){ // (3)
            if(row == s->columnindex[idx]){ // (4)
                s_new->rowpointer[row+1]++;
            }
        }
    }
    for(sparse_index_t i = 0; i < s_new->m; i++){
        s_new->rowpointer[i+1] += s_new->rowpointer[i];
    }
    s_new->nnz = s_new->rowpointer[s_new->m];
    s_new->columnindex = malloc(sizeof(sparse_index_t) * s_new->nnz);
    s_new->value = malloc(sizeof(sparse_value_t) * s_new->nnz);

    sparse_pointer_t* tmp_ptr = malloc(sizeof(sparse_pointer_t) * (s_new->m + 1));
    memcpy(tmp_ptr, s_new->rowpointer, sizeof(sparse_pointer_t) * (s_new->m + 1));
    for(sparse_index_t row = 0; row < s->m; row++){
        for(sparse_pointer_t idx = s->rowpointer[row]; idx < s->rowpointer[row+1]; idx++){
            // if(s->value[idx] != 0){ // (2)
            // if(fabs(s->value[idx]) > 1e-40){ // (3)
            if(row == s->columnindex[idx]){ // (4)
                s_new->columnindex[tmp_ptr[row]] = s->columnindex[idx];
                s_new->value[tmp_ptr[row]] = s->value[idx];
                tmp_ptr[row]++;
            }
        }
    }
    free(tmp_ptr);
}